<template>
  <div class="app-container">
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h3>验收列表</h3>
      <el-button
        type="success"
        size="small"
        icon="el-icon-plus"
        @click="handleAdd"
      >
        可验收
      </el-button>
    </div>

    <!-- 自定义下划线，替代el-divider -->
    <div class="custom-divider" />
    <!-- 搜索区域使用 transform 包裹 -->
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wapper">
        <div>
          <el-form
            ref="searchForm"
            :model="listQuery"
            :inline="true"
            label-width="90px"
          >
            <el-form-item label="日期范围">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
                style="width: 350px"
                @change="handleDateChange"
              />
            </el-form-item>

            <el-form-item label="状态">
              <el-select
                v-model="listQuery.status"
                placeholder="请选择状态"
                clearable
                style="width: 150px"
                @change="handleStatusChange"
              >
                <el-option label="待验收" :value="0" />
                <el-option label="已验收" :value="1" />
              </el-select>
            </el-form-item>

            <el-form-item label="类型">
              <el-select
                v-model="listQuery.type"
                placeholder="请选择类型"
                clearable
                style="width: 150px"
                @change="handleTypeChange"
              >
                <el-option label="验收组验收" :value="0" />
                <el-option label="仓管验收" :value="1" />
                <el-option label="监理验收" :value="2" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleFilter">查询</el-button>
              <el-button @click="resetFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </el-collapse-transition>

    <!-- 操作按钮区域 -->
    <div class="table-operations">
      <!-- <el-button
          type="primary"
          size="small"
          class="filter-trigger"
          @click="isFilterVisible = !isFilterVisible"
        >
          {{ isFilterVisible ? "收起" : "检索" }}
          <i
            :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
          ></i>
        </el-button> -->
      <el-form
        ref="searchForm"
        :model="listQuery"
        :inline="true"
        label-width="90px"
      >
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            style="width: 350px"
            @change="handleDateChange"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="listQuery.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
            @change="handleStatusChange"
          >
            <el-option label="待验收" :value="0" />
            <el-option label="已验收" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="类型">
          <el-select
            v-model="listQuery.type"
            placeholder="请选择类型"
            clearable
            style="width: 150px"
            @change="handleTypeChange"
          >
            <el-option label="验收组验收" :value="1" />
            <el-option label="仓管验收" :value="2" />
            <el-option label="监理验收" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- <el-button
          type="success"
          size="small"
          @click="handleAdd"
          icon="el-icon-plus"
        >
          可验收
        </el-button> -->
    </div>

    <!-- 商品表格区域 -->
    <el-table
      :data="acceptableLists"
      border
      style="width: 100%"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column> -->

      <el-table-column label="序号" type="index" width="60" align="center" />

      <el-table-column label="商品明细" width="900" align="center">
        <template slot-scope="scope">
          <div
            v-if="scope.row.list && scope.row.list.length > 0"
            class="goods-detail-container"
          >
            <!-- 循环渲染每个商品项 -->
            <div
              v-for="(item, index) in scope.row.list"
              :key="index"
              class="goods-item"
            >
              <div class="goods-row">
                <!-- 第一行：商品名称、仓库、数量、单价 -->
                <div class="goods-name">{{ item.goodsName }}</div>
                <div class="goods-type">{{ item.warehouseName }}</div>
                <div class="goods-number">
                  数量: <span class="number-value">{{ item.number }}</span>
                </div>
                <div class="goods-price">
                  单价: <span class="price-value">¥{{ item.unitPrice }}</span>
                </div>
                <div class="goods-tax-rate">
                  税率: <span class="tax-rate-value">{{ item.taxRate }}%</span>
                </div>
                <div class="goods-tax-price">
                  税额:
                  <span class="tax-price-value">¥{{ item.taxPrice }}</span>
                </div>
                <div class="goods-total">
                  总价: <span class="total-value">¥{{ item.totalPrice }}</span>
                </div>
                <div class="goods-tax-total">
                  含税:
                  <span class="tax-total-value">¥{{ item.totalTaxPrice }}</span>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="no-goods">暂无商品</div>
        </template>
      </el-table-column>

      <!-- <el-table-column
        prop="remark"
        label="备注"
        min-width="120"
        show-overflow-tooltip
      /> -->

      <el-table-column prop="status" label="状态" width="width" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="type" label="类型">
        <template slot-scope="scope">
          <el-tag :type="getTypeTagType(scope.row.type)">
            {{ getTypeName(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        align="center"
      >
        <template slot-scope="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>

      <!-- <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button
            type="warning"
            size="small"
            @click="handleCheck(scope.row)"
            :disabled="scope.row.status === 2"
            :title="
              scope.row.status === 2 ? '该项目已发起入库，无法再次验收' : ''
            "
          >
            验收
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        style="text-align: right"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 合计行 -->
    <!-- <div class="summary-row">
        <div class="summary-label">合计:</div>
        <div style="flex-grow: 1"></div>
        <div style="margin-right: 15px">数量: {{ totalQuantity }}</div>
      </div> -->

    <!-- 备注区域 -->
    <!-- <div class="remark-container" style="margin-top: 20px">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="备注信息"
          v-model="orderData.remark"
        >
        </el-input>
      </div> -->

    <!-- 金额信息区域 -->
    <!-- <div class="amount-container">
        <div class="amount-row">
          <div class="amount-item">
            <span class="amount-label">优惠率(%):</span>
            <el-input
              v-model="orderData.discountRate"
              class="amount-input"
            ></el-input>
          </div>

          <div class="amount-item">
            <span class="amount-label">优惠金额:</span>
            <el-input
              v-model="orderData.discountAmount"
              class="amount-input"
            ></el-input>
          </div>

          <div class="amount-item">
            <span class="amount-label">优惠后金额:</span>
            <el-input
              v-model="orderData.discountedAmount"
              class="amount-input"
              readonly
            ></el-input>
          </div>

          <div class="amount-item">
            <span class="amount-label">交货方式:</span>
            <el-select
              v-model="orderData.deliveryMethod"
              placeholder="请选择"
              class="amount-input wider"
            >
              <el-option
                v-for="item in deliveryMethodOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </div> -->

    <!-- 底部工具栏 -->
    <!-- <div class="footer-toolbar">
        <div class="custom-field">
          <el-link type="primary" class="blue-text">
            <i class="el-icon-plus"></i> 自定义字段
          </el-link>
        </div>

        <div class="history-buttons">
          <el-button size="small" class="history-btn">历史单据</el-button>
          <el-button size="small" class="history-btn">操作日志</el-button>
        </div>
      </div> -->

    <!-- 分页组件 -->
    <!-- <el-row
        :gutter="10"
        style="margin-top: 20px"
        type="flex"
        justify="end"
        v-if="false"
      >
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-row> -->

    <!-- 新增弹框 -->
    <el-dialog title="可验收列表" :visible.sync="addDialogVisible" width="80%">
      <!-- 调试信息 -->
      <div style="margin-bottom: 10px">
        <small
          >数据条数: {{ acceptableList ? acceptableList.length : 0 }}</small
        >
      </div>

      <!-- 有数据时显示列表 -->
      <template v-if="acceptableList && acceptableList.length > 0">
        <div
          v-for="order in acceptableList"
          :key="order.id"
          class="order-container"
        >
          <div class="order-header">
            <h4>{{ formatTime(order.createTime) }}</h4>
            <div>负责人: {{ order.directorName || "未指定" }}</div>
            <div v-if="order.remark">备注: {{ order.remark }}</div>
          </div>

          <!-- 商品明细表格 -->
          <div v-if="order.list && order.list.length > 0">
            <el-table
              :data="order.list"
              border
              style="width: 100%; margin-bottom: 20px"
              :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
              @selection-change="
                (selections) => handleSelectionListChange(selections, order.id)
              "
              :row-class-name="getRowClassName"
            >
              <el-table-column type="selection" width="55" align="center">
                <template>
                  <!-- 禁用行内选择框 -->
                  <el-checkbox disabled></el-checkbox>
                </template>
              </el-table-column>

              <!-- 其他列保持不变 -->
              <el-table-column label="仓库" width="120" align="center">
                <template slot-scope="scope">
                  {{ scope.row.warehouseName }}
                </template>
              </el-table-column>

              <el-table-column label="商品名称" width="150" align="center">
                <template slot-scope="scope">
                  {{ scope.row.goodsName }}
                </template>
              </el-table-column>

              <el-table-column label="数量" width="100" align="center">
                <template slot-scope="scope">
                  {{ scope.row.number }}
                </template>
              </el-table-column>

              <el-table-column label="单价" width="120" align="center">
                <template slot-scope="scope">
                  ¥ {{ formatNumber(scope.row.unitPrice) }}
                </template>
              </el-table-column>

              <el-table-column label="金额" width="120" align="center">
                <template slot-scope="scope">
                  ¥ {{ formatNumber(scope.row.totalPrice) }}
                </template>
              </el-table-column>

              <el-table-column label="税率" width="100" align="center">
                <template slot-scope="scope">
                  {{ scope.row.taxRate }}%
                </template>
              </el-table-column>

              <el-table-column label="税额" width="120" align="center">
                <template slot-scope="scope">
                  ¥ {{ formatNumber(scope.row.taxPrice) }}
                </template>
              </el-table-column>

              <el-table-column label="含税总价" width="120" align="center">
                <template slot-scope="scope">
                  ¥ {{ formatNumber(scope.row.totalTaxPrice) }}
                </template>
              </el-table-column>

              <!-- 操作列 - 只在第一行显示操作按钮 -->
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <!-- 只在每个订单的第一行显示操作按钮 -->
                  <div v-if="scope.$index === 0">
                    <el-button
                      size="mini"
                      :type="
                        getSelectedType(order.id) === 1 ||
                        getSelectedType(order.id) === null
                          ? 'primary'
                          : 'default'
                      "
                      @click="handleAccept(order.id, 1)"
                      >验收组</el-button
                    >
                    <el-button
                      size="mini"
                      :type="
                        getSelectedType(order.id) === 2 ? 'success' : 'default'
                      "
                      @click="handleAccept(order.id, 2)"
                      >仓管</el-button
                    >
                    <el-button
                      size="mini"
                      :type="
                        getSelectedType(order.id) === 3 ? 'warning' : 'default'
                      "
                      @click="handleAccept(order.id, 3)"
                      >监理</el-button
                    >
                  </div>
                  <!-- 其他行不显示操作按钮 -->
                  <span v-else>-</span>
                </template>
              </el-table-column>
            </el-table>

            <!-- 每个订单的摘要信息 -->
            <div class="order-summary">
              <span>数量合计: {{ calculateTotalQuantity(order.list) }}</span>
              <span
                >金额合计: ¥{{
                  formatNumber(calculateTotalAmount(order.list))
                }}</span
              >
              <span
                >含税合计: ¥{{
                  formatNumber(calculateTotalTaxAmount(order.list))
                }}</span
              >
            </div>
          </div>

          <!-- 显示无数据提示 -->
          <div v-else class="empty-data">
            <i class="el-icon-document"></i>
            <p>暂无商品明细</p>
          </div>
        </div>
      </template>

      <!-- 没有数据时显示提示 -->
      <div v-else class="no-data">
        <i class="el-icon-circle-close"></i>
        <p>没有可验收的数据</p>
      </div>

      <!-- 对话框底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSelectedItems"
          >批量验收</el-button
        >
      </div>
    </el-dialog>

    <!-- 批量验收类型选择弹框 -->
    <el-dialog
      title="批量验收"
      :visible.sync="batchCheckDialogVisible"
      width="500px"
    >
      <el-form ref="batchCheckForm" :model="checkForm" label-width="80px">
        <el-form-item label="类型">
          <el-radio-group v-model="checkForm.type">
            <el-radio :label="1">验收组验收</el-radio>
            <el-radio :label="2">仓管验收</el-radio>
            <el-radio :label="3">监理验收</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchCheckDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitBatchCheck">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAcceptableListApi,
  startAcceptanceApi,
  selCheckAcceptListApi,
} from "@/api/check_and_accept";
export default {
  name: "PurchaseDorder",
  data() {
    return {
      acceptableLists: [], // 列表数据
      // 分页相关
      listQuery: {
        page: 1,
        pageSize: 10,
        startTime: "",
        endTime: "",
        status: "",
        type: "",
      },
      isFilterVisible: false, // 控制筛选区域显示/隐藏
      scanEnabled: false,
      orderData: {
        supplier: "",
        salesPerson: "",
        orderDate: "2025-03-24",
        deliveryDate: "2025-03-24",
        orderType: "purchase",
        deliveryAddress: "",
        remark: "",
        discountRate: "0",
        discountAmount: "0",
        discountedAmount: "0.00",
        deliveryMethod: "",
      },
      salesPersonOptions: [
        { value: "admin", label: "管理员" },
        { value: "zhangsan", label: "张三" },
        { value: "lisi", label: "李四" },
      ],
      addressOptions: [
        { value: "address1", label: "广州市天河区某某路123号" },
        { value: "address2", label: "深圳市南山区某某路456号" },
      ],
      deliveryMethodOptions: [
        { value: "express", label: "快递" },
        { value: "self", label: "自提" },
        { value: "delivery", label: "送货" },
      ],
      warehouseOptions: [
        { value: "warehouse1", label: "主仓库" },
        { value: "warehouse2", label: "次仓库" },
      ],
      tableData: [
        {
          id: 1,
          productName: "",
          productImage: "",
          brand: "",
          productRemark: "",
          attribute: "",
          unit: "",
          warehouse: "",
          availableStock: 0,
          quantity: 0,
          batchNumber: "",
          packageType: "whole",
        },
        {
          id: 2,
          productName: "",
          productImage: "",
          brand: "",
          productRemark: "",
          attribute: "",
          unit: "",
          warehouse: "",
          availableStock: 0,
          quantity: 0,
          batchNumber: "",
          packageType: "whole",
        },
        {
          id: 3,
          productName: "",
          productImage: "",
          brand: "",
          productRemark: "",
          attribute: "",
          unit: "",
          warehouse: "",
          availableStock: 0,
          quantity: 0,
          batchNumber: "",
          packageType: "whole",
        },
        {
          id: 4,
          productName: "",
          productImage: "",
          brand: "",
          productRemark: "",
          attribute: "",
          unit: "",
          warehouse: "",
          availableStock: 0,
          quantity: 0,
          batchNumber: "",
          packageType: "whole",
        },
        {
          id: 5,
          productName: "",
          productImage: "",
          brand: "",
          productRemark: "",
          attribute: "",
          unit: "",
          warehouse: "",
          availableStock: 0,
          quantity: 0,
          batchNumber: "",
          packageType: "whole",
        },
      ],
      totalQuantity: 0,
      multipleSelection: [],
      total: 0,
      // 新增
      addDialogVisible: false,
      acceptableList: [], // 可验收列表
      warehouseList: [
        { id: 1, name: "仓库1" },
        { id: 2, name: "仓库2" },
        { id: 3, name: "仓库3" },
        { id: 4, name: "仓库4" },
      ], // 仓库列表，实际应该从接口获取
      batchCheckDialogVisible: false,
      dateRange: [], // 日期范围
      // 发起验收
      checkForm: {
        ids: [], // 改为数组，存储多选的ID
        type: 1,
      },
      acceptanceType: 1, // 默认验收类型：验收组
      selectedIds: [], // 选中的项目ID数组
      selectedItemsMap: {}, // 用于存储每个订单ID对应的选中项
      selectedRows: {}, // 用于存储每个订单中被选中的行索引
      selectedOrderIds: [], // 存储选中的订单ID
      selectedItemsData: null, // 存储选中的项目数据
      orderTypeMap: {}, // 用于存储每个订单ID对应的选中类型
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取列表数据
    async getList() {
      try {
        const res = await selCheckAcceptListApi(this.listQuery);
        this.acceptableLists = res.records;
        this.total = res.total;
      } catch (error) {
        console.error("获取列表失败:", error);
        this.$message.error("获取列表失败");
      }
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },

    // 重置
    resetFilter() {
      this.$refs.searchForm.resetFields();
      this.listQuery = {
        page: 1,
        pageSize: 20,
        startTime: "",
        endTime: "",
        status: "",
        type: "",
      };
      this.getList();
    },

    // 获取可验收列表
    async fetchAcceptableList() {
      try {
        const res = await getAcceptableListApi();
        if (res && res.code === 1 && res.data) {
          console.log("获取可验收列表成功:", res.data);
          this.acceptableList = res.data;
          this.initOrderTypes(); // 初始化订单类型
        } else {
          console.error("获取可验收列表失败:", res);
          this.$message.error(res?.msg || "获取可验收列表失败");
        }
      } catch (error) {
        console.error("获取可验收列表异常:", error);
        this.$message.error(
          "获取可验收列表异常: " + (error.message || "未知错误")
        );
      }
    },
    // 新增可验收
    handleAdd() {
      this.fetchAcceptableList();
      this.$nextTick(() => {
        this.addDialogVisible = true;
      });
    },

    // 格式化时间戳（Unix时间戳）
    formatTime(timestamp) {
      if (!timestamp) return "未知时间";

      // 确保时间戳是数字并转换为毫秒
      const ts = parseInt(timestamp) * 1000;

      try {
        const date = new Date(ts);

        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          return "无效日期";
        }

        // 格式化为 YYYY-MM-DD HH:MM:SS
        return (
          date.getFullYear() +
          "-" +
          String(date.getMonth() + 1).padStart(2, "0") +
          "-" +
          String(date.getDate()).padStart(2, "0") +
          " " +
          String(date.getHours()).padStart(2, "0") +
          ":" +
          String(date.getMinutes()).padStart(2, "0") +
          ":" +
          String(date.getSeconds()).padStart(2, "0")
        );
      } catch (error) {
        console.error("日期格式化失败:", error);
        return "日期错误";
      }
    },

    // 获取行的类名
    getRowClassName({ row, rowIndex }) {
      // 所有行都添加红色边框样式
      return "disabled-row";
    },

    // 处理表格多选变化
    handleSelectionListChange(selections, orderId) {
      console.log("选择变化：", selections, "订单ID:", orderId);

      // 检查是否已经选中了这个订单
      const index = this.selectedOrderIds.indexOf(orderId);

      // 如果selections不为空，表示选中；如果为空，表示取消选中
      if (selections && selections.length > 0) {
        // 选中了订单，如果不在列表中就添加
        if (index === -1) {
          this.selectedOrderIds.push(orderId);
        }
      } else {
        // 取消选中，从列表中移除
        if (index !== -1) {
          this.selectedOrderIds.splice(index, 1);
        }
      }

      console.log("当前选中的订单IDs:", this.selectedOrderIds);
    },

    // 修改submitSelectedItems方法
    async submitSelectedItems() {
      if (this.selectedOrderIds.length === 0) {
        this.$message.warning("请选择要验收的订单");
        return;
      }

      try {
        // 构建请求参数数组 - 每个选中的订单ID对应一个对象
        // 从orderTypeMap中获取订单的验收类型，如果没有设置则默认为1
        const requestItems = this.selectedOrderIds.map((id) => ({
          id: parseInt(id),
          type: this.orderTypeMap[id] || 1,
        }));

        console.log("提交验收请求数据:", requestItems);

        // 显示加载中
        const loading = this.$loading({
          lock: true,
          text: "正在提交验收请求...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });

        // 调用验收API，传递包含多个对象的数组
        const res = await startAcceptanceApi(requestItems);

        // 关闭加载提示
        loading.close();

        if (res.code === 1) {
          // 显示成功消息
          this.$message.success(`成功提交 ${requestItems.length} 个验收请求`);

          // 关闭弹窗
          this.addDialogVisible = false;

          // 刷新列表
          this.getList();

          // 清空选中的数据
          this.selectedOrderIds = [];
          this.orderTypeMap = {};
          this.selectedItemsData = null;

          console.log("已清空选中数据");
        } else {
          this.$message.error(res.msg || "提交验收请求失败");
        }
      } catch (error) {
        console.error("验收提交失败:", error);
        this.$message.error("验收提交失败: " + (error.message || "未知错误"));
      }
    },

    // 计算总数量
    calculateTotal() {
      this.totalQuantity = this.tableData.reduce((sum, item) => {
        return sum + (Number(item.quantity) || 0);
      }, 0);
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    // 获取仓库名称
    getWarehouseName(warehouseId) {
      const warehouse = this.warehouseList.find(
        (item) => item.id === warehouseId
      );
      return warehouse ? warehouse.name : warehouseId;
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: "warning", // 待验收
        1: "success", // 已验收
        2: "primary", // 已发起入库
        "-1": "danger", // 验收不通过
      };
      return statusMap[status] || "info";
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: "待验收",
        1: "已验收",
        2: "已发起入库",
        "-1": "验收不通过",
      };
      return statusMap[status] || "未知状态";
    },

    // 获取订单的选中类型
    getSelectedType(orderId) {
      // 如果没有设置值或值为null，返回1表示默认选择验收组
      return this.orderTypeMap[orderId] || 1;
    },

    // 当获取列表数据后调用，初始化所有订单的默认验收类型
    initOrderTypes() {
      if (this.acceptableList && this.acceptableList.length > 0) {
        this.acceptableList.forEach((order) => {
          if (!this.orderTypeMap[order.id]) {
            this.$set(this.orderTypeMap, order.id, 1); // 默认使用验收组
          }
        });
      }
    },

    // 处理验收类型选择
    handleAccept(orderId, type) {
      // 使用Vue的$set方法确保响应式更新
      this.$set(this.orderTypeMap, orderId, type);

      // 构建并存储数据对象
      const acceptItem = {
        id: orderId,
        type: type,
      };

      // 保存到对象中
      this.selectedItemsData = {
        items: [acceptItem],
        timestamp: new Date().getTime(),
      };

      console.log("已保存验收数据:", this.selectedItemsData);
      this.$message.success(
        `已选择${type === 1 ? "验收组" : type === 2 ? "仓管" : "监理"}验收方式`
      );
    },

    // 日期改变
    handleDateChange(val) {
      if (val) {
        // 设置开始时间为当天的 00:00:00
        const startDate = new Date(val[0]);
        startDate.setHours(0, 0, 0, 0);
        this.listQuery.startTime = Math.floor(startDate.getTime() / 1000);

        // 设置结束时间为当天的 23:59:59
        const endDate = new Date(val[1]);
        endDate.setHours(23, 59, 59, 999);
        this.listQuery.endTime = Math.floor(endDate.getTime() / 1000);
      } else {
        this.listQuery.startTime = "";
        this.listQuery.endTime = "";
      }
    },
    // 状态改变
    handleStatusChange(val) {
      this.listQuery.page = 1;
      this.getList();
    },
    // 类型改变
    handleTypeChange(val) {
      this.listQuery.page = 1;
      this.getList();
    },
    // 处理对话框关闭
    handleDialogClose() {
      this.addDialogVisible = false;
      // 清空选中状态
      this.selectedIds = [];
      this.acceptanceType = 1;
    },
    // 计算总数量
    calculateTotalQuantity(list) {
      return list.reduce((sum, item) => sum + (Number(item.number) || 0), 0);
    },
    // 计算金额合计
    calculateTotalAmount(list) {
      return list.reduce(
        (sum, item) => sum + (Number(item.totalPrice) || 0),
        0
      );
    },
    // 计算含税合计
    calculateTotalTaxAmount(list) {
      return list.reduce(
        (sum, item) => sum + (Number(item.totalTaxPrice) || 0),
        0
      );
    },
    // 格式化数字
    formatNumber(value) {
      return Number(value).toLocaleString(undefined, {
        minimumFractionDigits: 2,
      });
    },
    // 确认批量验收
    async submitBatchCheck() {
      try {
        if (this.selectedOrderIds.length === 0) {
          this.$message.warning("请选择要验收的订单");
          return;
        }

        // 构建请求数据
        const requestData = this.selectedOrderIds.map((id) => ({
          id: parseInt(id), // 确保ID是数字类型
          type: this.checkForm.type,
        }));

        console.log("批量验收请求数据:", requestData);

        const loading = this.$loading({
          lock: true,
          text: "批量验收中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });

        // 调用验收API
        const res = await startAcceptanceApi(requestData);

        loading.close();

        if (res && res.code === 1) {
          this.$message.success("批量验收成功");
          // 关闭弹窗
          this.batchCheckDialogVisible = false;
          this.addDialogVisible = false;
          // 刷新列表
          this.fetchAcceptableList();
          // 清空选中状态
          this.selectedOrderIds = [];
        } else {
          this.$message.error(res?.msg || "批量验收失败");
        }
      } catch (error) {
        console.error("批量验收失败:", error);
        this.$message.error("批量验收失败: " + (error.message || "未知错误"));
      }
    },
    // 获取类型名称
    getTypeName(type) {
      const typeMap = {
        1: "验收组验收",
        2: "仓管验收",
        3: "监理验收"
      };
      return typeMap[type];
    },
    // 获取类型对应的标签颜色
    getTypeTagType(type) {
      const typeColorMap = {
        1: "primary",   // 验收组验收 - 蓝色
        2: "success",   // 仓管验收 - 绿色
        3: "warning"    // 监理验收 - 黄色
      };
      return typeColorMap[type] || "info";
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-wapper {
  margin-bottom: 15px;
}
.table-operations-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.table-operations {
  margin-bottom: 15px;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.shopping-entry {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  align-items: center;
}

.entry-buttons {
  display: flex;
}

.circle-btn {
  margin-right: 10px;
  border-radius: 20px;
}

.attachment-info {
  display: flex;
  align-items: center;
}

.upload-link {
  margin-right: 15px;
}

.product-header {
  display: flex;
  align-items: center;
}

.required-mark {
  color: #f56c6c;
  margin-right: 4px;
}

.product-select {
  color: #409eff;
  cursor: pointer;
}

.product-image {
  width: 50px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.product-image img {
  max-width: 100%;
  max-height: 100%;
}

.batch-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.batch-tag {
  background-color: #909399;
  color: white;
  font-size: 10px;
  padding: 0 4px;
  border-radius: 2px;
}

.info-header {
  display: flex;
  align-items: center;
}

.info-header .el-icon-question {
  margin-left: 4px;
  color: #909399;
  cursor: help;
}

/* 合计行 */
.summary-row {
  display: flex;
  background-color: #fdf6ec;
  padding: 10px 15px;
  font-weight: bold;
  border: 1px solid #ebeef5;
  border-top: none;
}

.summary-label {
  width: 50px;
}

/* 备注区域 */
.remark-container {
  margin-bottom: 20px;
}

/* 自定义下划线 */
.custom-divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 13px 0;
}

/* 金额信息区域 */
.amount-container {
  margin-bottom: 20px;
}

.amount-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.amount-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 10px;
}

.amount-label {
  white-space: nowrap;
  margin-right: 5px;
  width: 80px;
  text-align: right;
}

.amount-input {
  width: 120px;
}

.amount-input.wider {
  width: 150px;
}

/* 底部工具栏 */
.footer-toolbar {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.blue-text {
  color: #409eff;
}

.history-buttons .history-btn {
  margin-left: 10px;
}

.blue-radio.el-radio ::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: #409eff;
}

.address-edit {
  margin-left: 5px;
  cursor: pointer;
  color: #409eff;
}

.el-table .cell {
  text-align: center;
}

.el-tag {
  margin: 0 auto;
}

.operation-btn {
  color: #409eff;
}

/* 商品明细样式 */
.goods-detail-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  text-align: left;
  padding: 5px;
}

.goods-item {
  display: flex;
  flex-direction: column;
  padding: 8px 0;
}

.goods-row {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.goods-row:last-child {
  margin-bottom: 0;
}

/* 第一行样式 */
.goods-name {
  width: 120px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 10px;
}

.goods-type {
  width: 120px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-number {
  width: 100px;
  color: #606266;

  .number-value {
    color: #409eff;
    font-weight: 500;
  }
}

.goods-price {
  width: 120px;
  color: #606266;

  .price-value {
    color: #67c23a;
    font-weight: 500;
  }
}

/* 第二行样式 */
.goods-tax-rate {
  width: 120px;
  color: #606266;
  padding-left: 10px;

  .tax-rate-value {
    color: #909399;
  }
}

.goods-tax-price {
  width: 120px;
  color: #606266;

  .tax-price-value {
    color: #e6a23c;
  }
}

.goods-total {
  width: 100px;
  color: #606266;

  .total-value {
    color: #f56c6c;
    font-weight: 500;
  }
}

.goods-tax-total {
  width: 120px;
  color: #606266;

  .tax-total-value {
    color: #f56c6c;
    font-weight: 500;
  }
}

.order-container {
  margin-bottom: 30px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.order-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #ebeef5;

  h4 {
    margin: 0 0 5px 0;
    color: #303133;
  }
}

.order-summary {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;

  span {
    margin-left: 20px;
    font-weight: bold;
    color: #606266;

    &:last-child {
      color: #f56c6c;
    }
  }
}

.empty-data,
.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px 0;
  color: #909399;

  i {
    font-size: 40px;
    margin-bottom: 10px;
  }

  p {
    margin: 0;
    font-size: 14px;
  }
}

/* 添加一些响应式样式 */
@media screen and (max-width: 768px) {
  .order-summary {
    flex-direction: column;

    span {
      margin: 5px 0;
    }
  }
}

.selected-row {
  background-color: #ffefef !important; /* 红色背景 */
  color: #f56c6c;
}

/* 为所有行添加红色边框样式 */
.el-table .disabled-row td {
  border: 1px solid #f56c6c !important;
}

/* 禁用鼠标悬停效果 */
.el-table .disabled-row:hover {
  cursor: not-allowed;
}
</style>
